<?php

namespace app\index\service;

use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\model\ConsultingServer;
use app\index\dao\ConsultingDao;
use app\index\model\UM as UM;
use app\index\traits\MessageSendTrait;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class FreeMatchService
 * @package app\index\service
 * @deprecated
 */
class FreeMatchService
{
    use MessageSendTrait;

    // dao
    private ConsultingDao $consultingDao;

    public function __construct(ConsultingDao $consultingDao)
    {
        $this->consultingDao = $consultingDao;
    }

    /**
     * 不悬赏
     * @param UM $user
     * @param array $params
     * @deprecated
     */
    public function add(UM $user, array $params): void
    {
        $consultingId = $params['consultingId'] ?? null;
        if (!is_id($consultingId)) {
            throw new ValidateException('请选择一个咨询');
        }

        $consulting = Consulting::field(true)->where('id', $consultingId)->find();

        if (is_null($consulting)) {
            throw new DataNotExistException('该咨询不存在或已被删除');
        }

        if (is_id($consulting->lawyerId)) {
            throw new ValidateException('该咨询已经匹配律师');
        }
        if ($consulting->matchType != Consulting::MATCH_TYPE_RANDOM) {
            throw new ValidateException('该咨询不能随机匹配');
        }
        if ($consulting->consultingType != 0) {
            throw new ValidateException('免费咨询才能立即随机匹配律师');
        }

        // 如果是随机匹配模式
        // 百分比卡片
        $content1 = [
            'text' => '正在为您优先匹配金牌律师，请稍等....'
        ];
        $this->getMessageSendService()->sendRobotMessage($consulting, null, 0, ConsultingMessage::TEXT, $content1);

        // 立即随机分配一个律师
        $this->getConsultingLawyerMatchService()->matchRand($consulting);

        // 激活免费服务
        if ($consulting->consultingType == 0 && is_id($consulting->consultingServerId)) {

            // 初始免费服务
            $freeServer = ConsultingServer::where('id', $consulting->consultingServerId)
                ->where('serverType', ConsultingServer::FREE)
                ->find();

            if ($freeServer) {
                // 免费服务生效
                event('FreeConsultingServerStart', ['consulting' => $consulting, 'server' => $freeServer]);
            }
        }

    }

    private function getConsultingLawyerMatchService(): ConsultingLawyerMatchService
    {
        return app(ConsultingLawyerMatchService::class);
    }

}
